<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        //方法1 ES10 新增Array.flat()
        let arr = [1, 2, 3, [4, 5, 6, [7, 8, 9, [10, 11, 12]]]];
        arr.flat() == arr.flat(1);               // [1,2,3,4,5,6,Array(4)]
        arr.flat().flat() == arr.flat(2);        // [1,2,3,4,5,6,7,8,9,Array(3)]
        arr.flat().flat().flat() == arr.flat(3); // [1,2,3,4,5,6,7,8,9,10,11,12]
        arr.flat(Infinity);       // [1,2,3,4,5,6,7,8,9,10,11,12]

        //如果数组的元素都是数字，可以使用该方法
        // 方法2
        var arr = [1, [2, [3, 4]]];

        console.log(arr.toString());//1,2,3,4
        console.log(arr.toString().split(','));//["1", "2", "3", "4"]把字符串分割为字符串数组。

        function flatten(arr) {
            return arr.toString().split(',').map(
                item => +item // +会使字符串发生类型转换
            )
        }//这个方法最好
        console.log(flatten(arr))//[1, 2, 3, 4]

        var arr1 = [1, [2, [3, 4]]];
        console.log(...arr1);//1,[2, [3, 4]
        console.log([].concat(...arr1)); // [1, 2, [3, 4]] 注意扩展运算符只能扁平化一层数组
        //改造一下，加上循环
        function flatten2(arr) {
            while (arr.some(item => Array.isArray(item))) {
                arr = [].concat(...arr);
            }
            return arr;
        }

        console.log(flatten2(arr1))//[1, 2, 3, 4]
    </script>
</body>

</html>